package com.gy.algorithm.carl.linklistexa;

/**
 * @BelongsProject: javabase
 * @BelongsPackage: com.gy.algorithm.carl
 * @Author: gy
 * @Date: 2024/10/22 11:30
 * @Description:
 */
public class ReverseList206 {
    public static void main(String[] args) {
        ListNode head5 = new ListNode(5);
        ListNode head4 = new ListNode(4, head5);
        ListNode head3 = new ListNode(3, head4);
        ListNode head2 = new ListNode(2, head3);
        ListNode head1 = new ListNode(1, head2);

        ListNode listNode = reverseList2(head1);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    // end
    public static ListNode reverseList(ListNode head) {
        return reverse(null,head);
    }

    public static ListNode reverse(ListNode pre,ListNode cur) {
        if(cur == null){
            return pre;
        }

        ListNode temp = cur.next;
        cur.next = pre;

        return reverse(cur,temp);
    }

    // end
    public static ListNode reverseList2(ListNode head) {
        ListNode cur = head;
        ListNode pre = null;

        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;

            pre = cur;
            cur = next;
        }

        return pre;
    }

    // write
    public static ListNode reverseList1(ListNode head) {
        if (null == head || head.next == null) return head;

        ListNode fast = head.next;
        ListNode low = head;

        low.next = null;
        ListNode next = null;

        while (fast != null) {
            next = fast.next;
            fast.next = low;
            low = fast;
            fast = next;
        }

        return low;
    }


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
